<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/notice' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>信息管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生信息</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card shadow="never">
      <!-- 搜索框区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入学生姓名"
            v-model="queryInfo"
            size="small"
            clearable
            @change="getStudentList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getStudentList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="showAddDialog">添加学生</el-button>
        </el-col>
      </el-row>
      <!-- 学生列表 -->
      <el-table :data="studentData" border stripe>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="right" class="tabExpand" inline>
              <el-form-item label="民族:">
                <el-tag>{{ props.row.detail.nation }}</el-tag>
              </el-form-item>
              <el-form-item label="籍贯:">
                <el-tag>{{ props.row.detail.origo }}</el-tag>
              </el-form-item>
              <el-form-item label="出生日期:">
                <el-tag>{{dayjs(props.row.detail.birthday).format("YYYY-MM-DD")}}</el-tag>
              </el-form-item>
              <el-form-item label="政治面貌:">
                <el-tag>{{ props.row.detail.visage }}</el-tag>
              </el-form-item>
              <el-form-item label="专业名称:">
                <el-tag>{{ props.row.detail.major }}</el-tag>
              </el-form-item>
              <el-form-item label="行政班级:">
                <el-tag>{{ props.row.detail.class }}</el-tag>
              </el-form-item>
              <el-form-item label="入学时间:">
                <el-tag>{{dayjs(props.row.detail.enrol).format("YYYY-MM-DD")}}</el-tag>
              </el-form-item>
              <el-form-item label="学历层次:">
                <el-tag v-if="props.row.detail.degree === 4">本科</el-tag>
                <el-tag v-else>专科</el-tag>
              </el-form-item>
              <el-form-item label="身份证号:">
                <el-tag>{{ props.row.detail.identify }}</el-tag>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column label="性别" width="50">
          <template slot-scope="scope">
            <i v-if="scope.row.sex === 1" class="el-icon-male male"></i>
            <i v-else class="el-icon-female female"></i>
          </template>
        </el-table-column>
        <el-table-column prop="sequence" label="编号"></el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">{{dayjs(scope.row.createTime).format("YYYY-MM-DD")}}</template>
        </el-table-column>
        <el-table-column prop="college" label="归属"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="状态" width="60">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.state === 1" :hit="true" size="mini">启用</el-tag>
            <el-tag type="info" v-else :hit="true" size="mini">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-edit"
              @click="showAmendDialog(scope.row._id)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="isDeleteStudent(scope.row._id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页按钮 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paging.page"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="paging.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paging.total"
      ></el-pagination>
    </el-card>
    <!-- 添加学生信息的对话框 -->
    <el-dialog
      title="添加学生"
      :visible.sync="addDialogVisible"
      width="50%"
      center
      @close="()=>{this.$refs.addFormRef.resetFields();removeUploadImg()}"
    >
      <!-- 添加信息表单 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="100px"
        size="medium"
        :rules="addFormRules"
        status-icon
      >
        <el-form-item label="姓名:" prop="username">
          <el-input
            v-model="addForm.username"
            prefix-icon="el-icon-user"
            placeholder="请输入学生姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="addForm.sex" size="mini">
            <el-radio-button :label="1">男</el-radio-button>
            <el-radio-button :label="0">女</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态:" prop="state">
          <el-radio-group v-model="addForm.state" size="mini">
            <el-radio :label="1" border>启用</el-radio>
            <el-radio :label="0" border>禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="email:" prop="email">
          <el-input
            v-model="addForm.email"
            prefix-icon="el-icon-message"
            placeholder="请输入邮箱地址"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input
            v-model="addForm.password"
            prefix-icon="el-icon-key"
            placeholder="请输入密码"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="上传头像:">
          <el-upload
            action="http://127.0.0.1:666/api/v1/upload"
            list-type="picture-card"
            :headers="addHeader"
            :auto-upload="false"
            :limit="1"
            :http-request="customUpload"
            ref="upload"
          >
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
              <span class="el-upload-list__item-actions">
                <!-- 预览按钮 -->
                <span @click="previewUploadImg(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <!-- 删除按钮 -->
                <span @click="removeUploadImg(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属学院:" prop="college">
          <el-select
            v-model="addForm.college"
            filterable
            default-first-option
            clearable
            placeholder="请选择所属学院"
            @focus="getCollegeList"
            no-match-text="没有这个选项"
            no-data-text="获取数据失败..."
          >
            <el-option v-for="item in colleges" :key="item.id" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更多:">
          <el-button icon="el-icon-plus" type="info" plain @click="innerVisible=true">详细信息...</el-button>
        </el-form-item>
        <el-dialog width="50%" title="详细信息" :visible.sync="innerVisible" append-to-body>
          <el-form-item label="学历:" prop="detail.degree">
            <el-radio-group v-model="addForm.detail.degree">
              <el-radio-button :label="4">本科</el-radio-button>
              <el-radio-button :label="3">专科</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="籍贯:" prop="detail.origo">
            <el-cascader
              :options="origos"
              v-model="addForm.detail.origo"
              placeholder="请选择户籍所在"
              :props="{expandTrigger: 'hover',value:'label'}"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="民族:" prop="detail.nation">
            <el-input
              v-model="addForm.detail.nation"
              prefix-icon="el-icon-house"
              placeholder="请输入民族"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="班级:" prop="detail.class">
            <el-input
              v-model="addForm.detail.class"
              prefix-icon="el-icon-s-home"
              placeholder="请输入班级"
              type="number"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证号:" prop="detail.identify">
            <el-input
              v-model="addForm.detail.identify"
              prefix-icon="el-icon-coordinate"
              placeholder="请输入身份证号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="政治面貌:" prop="detail.visage">
            <el-select v-model="addForm.detail.visage" placeholder="请选择政治面貌">
              <el-option v-for="item in visages" :key="item.label" :value="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="专业名称:" prop="detail.major">
            <el-cascader
              v-model="addForm.detail.major"
              :options="colleges"
              :props="{expandTrigger: 'hover',value:'label'}"
              @focus="getCollegeList"
              :show-all-levels="false"
              placeholder="请选择专业名称"
              filterable
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="入学时间:" prop="detail.enrol">
            <el-date-picker v-model="addForm.detail.enrol" type="date" placeholder="请选择入学时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="出生日期:" prop="detail.birthday">
            <el-date-picker v-model="addForm.detail.birthday" type="date" placeholder="请选择出生年月"></el-date-picker>
          </el-form-item>
          <span slot="footer">
            <el-button @click="innerVisible = false">取 消</el-button>
            <el-button type="primary" @click="innerVisible=false">确 定</el-button>
          </span>
        </el-dialog>
      </el-form>

      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addStudent">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 预览图片对话框 -->
    <el-dialog :visible.sync="previewDialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
    <!-- 修改学生信息对话框 -->
    <el-dialog
      title="修改信息"
      :visible.sync="amendDialogVisible"
      width="50%"
      center
      @close="removeUploadImg"
    >
      <!-- 修改信息表单 -->
      <el-form
        ref="amendFormRef"
        :model="studentInfo"
        label-width="100px"
        size="medium"
        :rules="addFormRules"
        status-icon
      >
        <el-form-item label="姓名:" prop="username">
          <el-input
            v-model="studentInfo.username"
            prefix-icon="el-icon-user"
            placeholder="请输入学生姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="studentInfo.sex" size="mini">
            <el-radio-button :label="1">男</el-radio-button>
            <el-radio-button :label="0">女</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态:" prop="state">
          <el-radio-group v-model="studentInfo.state" size="mini">
            <el-radio :label="1" border>启用</el-radio>
            <el-radio :label="0" border>禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="email:" prop="email">
          <el-input
            v-model="studentInfo.email"
            prefix-icon="el-icon-message"
            placeholder="请输入邮箱地址"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input
            v-model="studentInfo.password"
            prefix-icon="el-icon-key"
            placeholder="请输入密码"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="上传头像:">
          <el-upload
            action="http://127.0.0.1:666/api/v1/upload"
            list-type="picture-card"
            :headers="addHeader"
            :auto-upload="false"
            :http-request="customUpload"
            :limit="1"
            ref="upload"
          >
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
              <span class="el-upload-list__item-actions">
                <!-- 预览按钮 -->
                <span @click="previewUploadImg(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <!-- 删除按钮 -->
                <span @click="removeUploadImg(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属学院:" prop="college">
          <el-select
            v-model="studentInfo.college"
            filterable
            default-first-option
            clearable
            placeholder="请选择所属学院"
            @focus="getCollegeList"
            no-match-text="没有这个选项"
            no-data-text="获取数据失败..."
          >
            <el-option v-for="item in colleges" :key="item.id" :value="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更多:">
          <el-button
            icon="el-icon-plus"
            type="info"
            plain
            @click="()=>{amendInnerVisible=true;this.detailInfo=this.studentInfo.detail}"
          >详细信息...</el-button>
        </el-form-item>
        <el-dialog width="50%" title="详细信息" :visible.sync="amendInnerVisible" append-to-body>
          <el-form-item label="学历:" prop="detail.degree">
            <el-radio-group v-model="detailInfo.degree">
              <el-radio-button :label="4">本科</el-radio-button>
              <el-radio-button :label="3">专科</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="籍贯:" prop="detail.origo">
            <el-cascader
              :options="origos"
              v-model="detailInfo.origo"
              placeholder="请选择户籍所在"
              :props="{expandTrigger: 'hover',value:'label'}"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="民族:" prop="detail.nation">
            <el-input
              v-model="detailInfo.nation"
              prefix-icon="el-icon-house"
              placeholder="请输入民族"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="班级:" prop="detail.class">
            <el-input
              v-model="detailInfo.class"
              prefix-icon="el-icon-s-home"
              placeholder="请输入班级"
              type="number"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证号:" prop="detail.identify">
            <el-input
              v-model="detailInfo.identify"
              prefix-icon="el-icon-coordinate"
              placeholder="请输入身份证号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="政治面貌:" prop="detail.visage">
            <el-select v-model="detailInfo.visage" placeholder="请选择政治面貌">
              <el-option v-for="item in visages" :key="item.label" :value="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="专业名称:" prop="detail.major">
            <el-cascader
              v-model="detailInfo.major"
              :options="colleges"
              :props="{expandTrigger: 'hover',value:'label'}"
              @focus="getCollegeList"
              :show-all-levels="false"
              placeholder="请选择专业名称"
              filterable
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="入学时间:" prop="detail.enrol">
            <el-date-picker v-model="detailInfo.enrol" type="date" placeholder="请选择入学时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="出生日期:" prop="detail.birthday">
            <el-date-picker v-model="detailInfo.birthday" type="date" placeholder="请选择出生年月"></el-date-picker>
          </el-form-item>
          <span slot="footer">
            <el-button @click="amendInnerVisible = false">取 消</el-button>
            <el-button type="primary" @click="amendInnerVisible=false">确 定</el-button>
          </span>
        </el-dialog>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="amendDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateSInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { regionData } from 'element-china-area-data'
export default {
  data() {
    // 自定义校验邮箱规则
    let checkEamil = (rule, value, cbfn) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!regEmail.test(value)) {
        cbfn(new Error('请输入正确的邮箱格式'))
      } else {
        cbfn()
      }
    }
    // 自定义校验身份证号规则
    let checkId = (rule, value, cbfn) => {
      // 验证身份id的正则表达式
      const regId = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      if (!regId.test(value)) {
        cbfn(new Error('请输入正确的身份证号'))
      } else {
        cbfn()
      }
    }
    return {
      // 存放查询信息
      queryInfo: '',
      // 存放学生列表
      studentData: [],
      // 存放分页数据
      paging: {
        // 存放当前所在页数
        page: 1,
        // 存放页面呈现数据
        size: 1,
        // 数据总条数
        total: 0
      },
      // 控制添加学生信息的对话框是否显示
      addDialogVisible: false,
      // 存储添加表单信息
      addForm: {
        username: '',
        password: '',
        email: '',
        sex: 1,
        state: 1,
        avatar: '',
        college: '',
        detail: {
          birthday: '',
          nation: '',
          visage: '',
          major: [],
          origo: '',
          class: 1,
          enrol: '',
          degree: 4,
          identify: ''
        }
      },
      // 存储学院信息
      colleges: [],
      // 控制预览图片的对话框是否显示
      previewDialogVisible: false,
      // 存储预览对图片话框的图片路径
      dialogImageUrl: '',
      // 手动添加到头部的token信息
      addHeader: {
        Authorization: window.localStorage.getItem('token')
      },
      // 添加表单的验证规则
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入学生姓名',
            trigger: 'blur'
          },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        state: [{ required: true, message: '请选择状态', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮件地址', trigger: 'blur' },
          { validator: checkEamil, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        college: [{ required: true, message: '请选择学院', trigger: 'blur' }],
        detail: {
          birthday: [
            {
              required: true,
              message: '请选择出生年月',
              trigger: 'blur'
            }
          ],
          nation: [
            {
              required: true,
              message: '请输入民族',
              trigger: 'blur'
            }
          ],
          visage: [
            {
              required: true,
              message: '请选择政治面貌',
              trigger: 'blur'
            }
          ],
          major: [
            {
              required: true,
              message: '请选择专业',
              trigger: 'blur'
            }
          ],
          class: [
            {
              required: true,
              message: '请输入班级',
              trigger: 'blur'
            }
          ],
          identify: [
            {
              required: true,
              message: '请输入身份证号',
              trigger: 'blur'
            },
            { validator: checkId, trigger: 'blur' }
          ],
          enrol: [
            {
              required: true,
              message: '请选择入学时间',
              trigger: 'blur'
            }
          ],
          degree: [
            {
              required: true,
              message: '请选择学历层次',
              trigger: 'blur'
            }
          ],
          origo: [
            {
              required: true,
              message: '请选择户籍所在',
              trigger: 'blur'
            }
          ]
        }
      },
      // 控制内层对话框是否可见
      innerVisible: false,
      // 存储政治面貌选项
      visages: [
        {
          label: '共青团员'
        },
        {
          label: '共产党员'
        },
        {
          label: '预备党员'
        },
        {
          label: '少先队员'
        }
      ],
      // 存储省市区信息
      origos: regionData,
      // 存储学生个人信息
      studentInfo: {},
      // 控制修改学生信息的外层对话框是否显示
      amendDialogVisible: false,
      // 控制修改学生信息的内层对话框是否显示
      amendInnerVisible: false,
      // 临时存储学生的详细信息
      detailInfo: {},
      // 标识操作为添加还是更新
      flag: false
    }
  },
  methods: {
    // 当页面呈现数据的条数改变时触发
    handleSizeChange(newSize) {
      // 更新数据
      this.paging.size = newSize
      // 刷新页面
      this.getStudentList()
    },
    // 当页数改变时触发
    handleCurrentChange(newPage) {
      // 更新数据
      this.paging.page = newPage
      // 刷新页面
      this.getStudentList()
    },
    // 获取学生列表
    async getStudentList() {
      let res = await this.$http.get('users', {
        params: {
          queryInfo: this.queryInfo,
          page: this.paging.page,
          size: this.paging.size,
          path: this.$router.history.current.path
        }
      })
      // 获取失败
      if (res.meta.status !== 200) {
        this.$message.error('获取学生列表失败')
      }
      // 获取成功
      this.studentData = res.data.userList
      // 获取数据总条数
      this.paging.total = res.data.total
    },
    // 控制添加对话框是否显示
    async showAddDialog() {
      // 打开对话框
      this.addDialogVisible = true
    },
    // 获取学院列表
    async getCollegeList() {
      // 向服务端发送请求
      let res = await this.$http.get('colleges')
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取学院列表失败')
      }
      // 获取成功
      this.colleges = res.data
    },
    // 删除要上传的图片
    removeUploadImg(file) {
      this.$refs.upload.clearFiles()
    },
    // 预览上传的图片
    previewUploadImg(file) {
      this.dialogImageUrl = file.url
      this.previewDialogVisible = true
    },
    async customUpload(content) {
      // 获取上传图片的后缀
      let suffix = content.file.name.split('.')[1]
      // 文件重命名
      let rename = 'upload_' + Date.now() + '.' + suffix
      // 保存图片路径
      this.addForm.avatar = 'uploads/' + rename
      // 创建form对象
      let params = new FormData()
      // 通过append向form对象添加数据
      params.append('file', content.file)
      // 添加自定义名字
      params.append('name', rename)
      // 判断是否在更新
      if (this.studentInfo._id) {
        // 保存图片路径
        this.studentInfo.avatar = 'uploads/' + rename
        // 添加id
        params.append('id', this.studentInfo._id)
      }
      // 上传图片
      await this.$http.post(content.action, params)
    },
    // 添加学生信息
    addStudent() {
      // 重置studentInfo
      this.studentInfo = {}
      // 验证表单
      this.$refs.addFormRef.validate(async valid => {
        // 如果验证失败，直接返回
        if (!valid) return
        // 上传头像
        this.$refs.upload.submit()
        // 用户没有上传头像，就使用默认头像
        if (this.addForm.avatar.length === 0) {
          this.addForm.avatar = 'uploads/logo.jpg'
        }
        // 获取提交表单中的detail字段
        let detail = this.addForm.detail
        // 发送请求前，格式化数据
        detail.major = this.formatMajor
        detail.nation = this.formatNation
        detail.origo = this.formatOrigo
        // 为提交表单添加当前页面所在路由
        this.addForm.path = this.$router.history.current.path
        // 向服务端发起请求
        let res = await this.$http.post('users', this.addForm)
        // 添加学生失败
        if (res.meta.status !== 201) {
          return this.$message.error('添加学生失败')
        }
        // 添加学生成功
        this.$message.success('添加学生成功')
        // 刷新列表
        this.getStudentList()
        // 关闭对话框
        this.addDialogVisible = false
        // 重置avatar
        this.addForm.avatar = ''
      })
    },
    // 触发删除学生的确认框
    async isDeleteStudent(id) {
      let result = await this.$confirm(
        '此操作将永久删除该帐号, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message.info('已取消删除')
      })

      if (result === 'confirm') {
        // 发起删除请求
        let res = await this.$http.delete('users', { params: { id } })
        // 删除失败
        if (res.meta.status !== 204) {
          return this.$message.error('删除失败')
        }
        // 删除成功
        this.$message.success('删除成功!')
        // 刷新列表
        this.getStudentList()
      }
    },
    // 控制修改对话框是否显示
    async showAmendDialog(id) {
      // 打开对话框
      this.amendDialogVisible = true
      // 获取教师信息
      this.getStudentInfo(id)
    },
    // 获取指定学生信息
    async getStudentInfo(id) {
      // 发起请求
      let res = await this.$http.get('/users/userInfo', { params: { id } })
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取学生信息失败')
      }
      // 获取成功
      this.studentInfo = res.data.userInfo
    },
    // 更新学生信息
    updateSInfo() {
      // 标识为更新操作
      this.flag = true
      // 验证表单
      this.$refs.amendFormRef.validate(async valid => {
        // 验证失败直接返回
        if (!valid) return
        // 上传头像
        this.$refs.upload.submit()
        // 将更新的详细信息添加到提交表单中
        this.studentInfo.detail = this.detailInfo
        // 获取提交表单中的detail字段
        let detail = this.studentInfo.detail
        // 发送请求前，格式化数据
        detail.major = this.formatMajor
        detail.nation = this.formatNation
        detail.origo = this.formatOrigo
        // 发送请求
        let res = await this.$http.put('users', this.studentInfo)
        // 更新失败
        if (res.meta.status !== 201) {
          return this.$message.error('更新学生信息失败')
        }
        // 更新成功
        this.$message.success('更新学生信息成功')
        // 刷新列表
        this.getStudentList()
        // 关闭对话框
        this.amendDialogVisible = false
        // 标识为添加操作
        this.flag = false
      })
    }
  },
  created() {
    // 获取学生列表
    this.getStudentList()
  },
  computed: {
    // 格式化专业名称
    formatMajor() {
      let form = this.flag ? this.studentInfo : this.addForm
      let arr = form.detail.major
      return arr[arr.length - 1]
    },
    // 格式化民族
    formatNation() {
      let form = this.flag ? this.studentInfo : this.addForm
      let str = form.detail.nation
      return str.includes('族') ? str : str + '族'
    },
    // 格式化籍贯
    formatOrigo() {
      let form = this.flag ? this.studentInfo : this.addForm
      let arr = form.detail.origo
      return arr.join('/')
    }
  }
}
</script>

<style lang="less">
.cell {
  .male {
    font-weight: bold;
    color: #acf0fd;
  }
  .female {
    font-weight: bold;
    color: #faa9b0;
  }
}
.tabExpand {
  font-size: 0;
}
.tabExpand label {
  width: 90px;
  color: #99a9bf;
}
.tabExpand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>